package jp.takapy.baycity.urayasu;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;

import jp.takapy.baycity.util.XMLUtils;

import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

public class TopActivity extends Activity {

	private static String TAG = "BaycityBusApp.TopActivity";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		String urlStr = "http://www.baycity-bus.co.jp/cgi-local/rosen_index.cgi?cd=091-H-12&nb=9";
		String encoding = "Shift-JIS";
		String noMeta = "<meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=Shift_JIS\">";
		String meta = "<meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=Shift_JIS\">\n" +
						"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n";

		try {
			Document document = parse(urlStr, encoding);
			Toast.makeText(this, "Operation Success !!", Toast.LENGTH_SHORT).show();
			//System.out.println("Operation Success !!");

			String html = XMLUtils.document2String(document);
			//Toast.makeText(this, html, Toast.LENGTH_LONG).show();

			String src = html.replaceAll(noMeta, meta);

	        WebView webView = (WebView) findViewById(R.id.webview);
	        webView.loadDataWithBaseURL("file:///android_asset/", src, "text/html", "utf-8", null);


			NodeList nl = document.getElementsByTagName("table");
			int maches = nl.getLength();

			//上りのみ or 上り＆下りかを判定
	        if (maches > 3) {

	        	//行先取得(1番目のtableタグ内)
	        	Element dirElement = (Element) nl.item(0);
	        	String dir = getElementContent(dirElement, "b");
	        	Toast.makeText(this, dir, Toast.LENGTH_SHORT).show();

	        	//平日時刻取得
	        	Element dayElement = (Element) nl.item(1);
	        	NodeList dayNodeList = dayElement.getElementsByTagName("tr");

	        	List<String> dayData = new ArrayList<String>();
	        	//StringBuffer dayDataSB = new StringBuffer();
	        	String dayDataStr = "";

	        	//tr(行数分)処理
	        	for (int i =0; i < dayNodeList.getLength(); i++) {

	        		//tdタグNodeList取得
	        		Element dayTdElement = (Element) dayNodeList.item(i);
	        		NodeList dayTdList = dayTdElement.getChildNodes();

		        	for (int j =0; j < dayTdList.getLength(); j++) {

		        		Node timeNode = dayTdList.item(j);
		        		Node content = timeNode.getFirstChild();
		        		String time = content.getNodeValue();
		        		dayData.add(time);
		        		//dayDataSB.append(time + "\n");
		        		dayDataStr = dayDataStr + time + "\n";
		        	}
	        	}

	        	Toast.makeText(this, dayDataStr, Toast.LENGTH_SHORT).show();

	        	//休日時刻取得
	        	Element holidayElement = (Element) nl.item(2);
	        	NodeList holidayNodeList = holidayElement.getElementsByTagName("tr");
	        	List<String> holidayData = new ArrayList<String>();
	        	StringBuffer holidayDataSB = new StringBuffer();
	        	//tr(行数分)処理
	        	for (int i =0; i < holidayNodeList.getLength(); i++) {

	        		//tdタグNodeList取得
	        		Element holiDayTdElement = (Element) dayNodeList.item(i);
	        		NodeList holiDayTdList = holiDayTdElement.getChildNodes();

		        	for (int j =0; j < holiDayTdList.getLength(); j++) {

		        		Node timeNode = holiDayTdList.item(j);
		        		Node content = timeNode.getFirstChild();
		        		String time = content.getNodeValue();
		        		holidayData.add(time);
		        		holidayDataSB.append(time + "\n");
		        	}
	        	}
	        	Toast.makeText(this, holidayDataSB.toString(), Toast.LENGTH_SHORT).show();
	        }



/*
			for (int i = 0; i < maches; i++) {
				Element e = (Element)nl.item(i);


				Log.d(TAG, getElementContent(e, "b"));
				if (getElementContent(e, "b") != null) {
					Toast.makeText(this, getElementContent(e, "b"), Toast.LENGTH_SHORT).show();
				}

			}
*/

		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}

	}


	public static Document parse(String url, String encoding)
			throws IOException {

		if (url == null || url.length() == 0) {
			throw new IllegalArgumentException("urlがnullか空です");
		}

		if (encoding == null || encoding.length() == 0) {
			throw new IllegalArgumentException("encodingがnullか空です");
		}

		InputStream stream = null;
		try {
			stream = new URL(url).openStream();

			InputSource source = new InputSource(stream);
			source.setEncoding(encoding);

			try {
				XMLReader reader = new Parser();
				reader.setFeature(Parser.namespacesFeature, false);
				reader.setFeature(Parser.namespacePrefixesFeature, false);

				Transformer transformer = TransformerFactory.newInstance()
						.newTransformer();

				DOMResult result = new DOMResult();
				transformer.transform(new SAXSource(reader, source), result);

				return (Document) result.getNode();

			} catch (SAXException e) {

				// Parser.setFeatureは失敗しないはず。
				throw new RuntimeException(e);

			} catch (TransformerException e) {

				// これに失敗してるようではどうしようもない。
				throw new RuntimeException(e);
			}

		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	// アイテム要素から各子要素の内容を取り出す（5）
	static String getElementContent(Element e, String TagName) {
	NodeList nl = e.getElementsByTagName(TagName);
	Node n = nl.item(0);
	Node content = n.getFirstChild();
	return content.getNodeValue();
	}

}
